<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>迈阿密</title>
</head>

<body>
  <ul>

  </ul>
  <input type="text" id="message">
  <button id="btn_send">发送</button>
  <script>
    // 1.获取dom节点
    const oUl = document.querySelector('ul');
    const iMessage = document.querySelector('#message');
    const btnSend = document.querySelector('#btn_send');

    // 建立webSocket连接
    const ws = new WebSocket('ws://localhost:8000');

    // 发送按钮点击事件
    btnSend.onclick = function () {

      let data = {
        user: sessionStorage.getItem('username'),
        dateTime: new Date().getTime(),
        msg: iMessage.value
      }

      // ws发送数据
      ws.send(JSON.stringify(data));

      // 置空输入框
      iMessage.value = null
    }

    function bindEvent() {
      ws.addEventListener('open', openHandler);
      ws.addEventListener('close', closeHandler);
      ws.addEventListener('error', erroeHandler);
      ws.addEventListener('message', messageHandler);

      function openHandler() {
        console.log('WebSocket open');
      }
      function closeHandler() {
        console.log('WebSocket close');
      }
      function erroeHandler() {
        console.log('WebSocket error');
      }
      function messageHandler(e) {
        let data = JSON.parse(e.data);
        // 根据数据生成dom节点
        oUl.appendChild(createLi(data));

        function createLi(data) {
          let oLi = document.createElement('li');
          oLi.innerHTML = `
            <p>
              <span>`+ data.user + `</span>
              <i>`+ data.dateTime + `</i>
            </p>
            <p>消息：`+ data.msg + `</p>
          `;
          return oLi
        }
      }
    }

    bindEvent();



  </script>
</body>

</html>